<template>
  <div class="app-container">


    <el-autocomplete
      class="inline-input"
      v-model="example.company"
      :fetch-suggestions="queryCompanySearch"
      placeholder="公司名"
      style="width: 300px"
      :debounce="600"
    ></el-autocomplete>

    <el-cascader
      placeholder="工作地点"
      v-if="locationOptions"
      v-model="example.location"
      :options="locationOptions"
      :props="{ checkStrictly: true }"
      :show-all-levels="true"></el-cascader>

    <el-cascader
      placeholder="工作类型"
      v-if="typeOptions"
      v-model="example.type"
      :options="typeOptions"
      :props="{ checkStrictly: true }"
      :show-all-levels="false"></el-cascader>

    <span style="display: inline-flex;align-items: center;width:270px;margin-left: 15px">
        <span style="color:#606266;font-weight:700;font-size:14px;margin-right:20px !important;}">平均薪资范围</span>
        <el-slider v-model="sliderValue" :step="1" :max="100" style="width: 150px;" range></el-slider>
    </span>

    <el-button icon="el-icon-search" @click="fetchData" type="primary" round style="margin-left: 10px;">搜索</el-button>
    <el-button icon="el-icon-refresh" @click="reset" circle></el-button>


    <el-table :data="list" v-loading.body="listLoading" element-loading-text="加载数据中" fit
              highlight-current-row style="margin-top: 20px;">
      <el-table-column align="center" label='名称'>
        <template slot-scope="scope">
          <el-link :href="scope.row.positionDetailUrl"> {{scope.row.positionName}}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label='企业'>
        <template slot-scope="scope">
          <el-badge value="知名" class="item" type="warning" :hidden="scope.row.companyFamous === '0'">
            {{scope.row.companyFullname}}
          </el-badge>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.secondType +' > '+ scope.row.thirdType}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="薪资" width="120">
        <template slot-scope="scope">
          {{scope.row.salary}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="工作年限" width="110">
        <template slot-scope="scope">
          {{scope.row.workyear | workYearFilter}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="120">
        <template slot-scope="scope">

          <el-button @click="toModifydetail(scope.row)" type="text" circle size="small" style="padding: 2px"
                     icon="el-icon-edit">

          </el-button>
          <el-button @click="changeStatus(scope.row.id,0)" type="text" circle size="small" style="padding: 2px"
                     icon="el-icon-delete">

          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <Pagination
      :total="total"
      :page.sync="page"
      :limit.sync="limit"
      @pagination="fetchData"/>

    <el-dialog title="修改信息" :visible.sync="dialogFormVisible">
      <el-form :model="temp">
        <el-form-item label="职位名称" :label-width="formLabelWidth">
          <el-input v-model="temp.positionName"></el-input>
        </el-form-item>
        <el-form-item label="企业名称" :label-width="formLabelWidth">
          <el-input v-model="temp.companyFullname"></el-input>
        </el-form-item>
        <el-form-item label="薪资" :label-width="formLabelWidth">
          <el-input v-model="temp.salary"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="modifyData">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {search, modify, changeStatus, type, location, positionSearch, companySearch} from '@/api/position'
  import Pagination from '@/components/Pagination'
  import {mapGetters} from 'vuex'

  export default {
    components: {Pagination},
    data() {
      this.chartSettings = {

        area: true
      };
      return {
        list: null,
        listLoading: true,
        buttonLoading: false,
        dialogFormVisible: false,
        formLabelWidth: "120",
        total: 20,
        page: 1,
        limit: 10,
        example: {
          position: '',
          company: '',
          location: '',
          type: ''
        },
        sliderValue: [0, 100],
        temp: {},
        locationOptions: [],
        typeOptions: []

      }
    },
    filters: {
      playersFilter(data) {
        let players = JSON.parse(data);
        let result = '';
        for (let player of players) {
          result = result + ' ' + player + ' '
        }
        return result
      },
      dateReserve(timestamp) {
        var date = new Date(timestamp * 1000);
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() + 1 < 10 ? '0' + (date.getDate() + 1) : date.getDate() + 1);
        return Y + M + D;
      },
      workYearFilter(workYear) {
        const workYearMap = {
          '0': '不限',
          '1': '不限',
          '2': '应届毕业生',
          '3': '3年以下',
          '4': '3-5年',
          '5': '5-10年',
          '6': '10年以上'
        };
        return workYearMap[workYear]
      }
    },
    created() {
      this.fetchData();
      this.fetchOptions();
      this.checkLogin()
    },
    computed: {
      ...mapGetters([
        'uid'
      ]),
    },
    methods: {
      async logout() {
        await this.$store.dispatch('user/logout');
        this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      },
      checkLogin() {
        if (!this.uid) {
          this.logout();
          return false
        }
      },
      fetchOptions() {
        location().then(response => {
          this.locationOptions = response.data;
        });
        type().then(response => {
          this.typeOptions = response.data
        })
      },
      imgUrlComputed(bdidList) {
        var url = [];
        bdidList = JSON.parse(bdidList);
        for (let bdid of bdidList) {
          getImgUrl({
            bdid: bdid
          }).then(response => {
            url.push(response.data);
          })
        }
        return url
      }, //todo 异步问题未解决
      fetchData() {
        this.listLoading = true;
        search({
          page: this.page, limit: this.limit, uid: this.uid,
          position: this.example.position, company: this.example.company,
          location: this.example.location ? this.example.location[this.example.location.length - 1] : '',
          type: this.example.type ? this.example.type[this.example.type.length - 1] : '',
          slider_begin: this.sliderValue[0], slider_end: this.sliderValue[1]
        }).then(response => {
          this.list = response.data;
          this.total = response.count;
          this.listLoading = false
        })
      },
      reset() {
        for (var key in this.example) {
          this.example[key] = '';
        }
        this.sliderValue = [0, 100];
        this.fetchData();
      },
      toModifydetail(rowData) {
        this.temp = Object.assign({}, rowData);
        this.dialogFormVisible = true
      },
      modifyData() {
        this.buttonLoading = true;
        modify(this.temp).then(response => {
          this.buttonLoading = false;
          this.dialogFormVisible = false;
          this.$message({
            type: 'success',
            message: '修改成功'
          });
          this.fetchData()
        })
      },
      changeStatus(id, statusCode) {
        changeStatus({bdid: id, uid: this.uid, status: statusCode}).then(response => {
          // this.$message({
          //   type: 'success',
          //   message: response.msg
          // });
          let flag = 0;
          for (let item of this.list) {
            if (item['bdid'] === id) {
              if (statusCode === -1) {
                this.fetchData();
                return false
              }
              if (item['status'] === statusCode) {
                this.list[flag].status = 0
              } else {
                this.list[flag].status = statusCode
              }
            }
            flag += 1
          }

        })
      },
      queryPositionSearch(queryString, cb) {
        positionSearch({position: queryString}).then(response => {
          let list = [];
          response.data.forEach(element => {
            let object = {"value": element};
            list.push(object)
          });
          cb(list)
        })
      },
      queryCompanySearch(queryString, cb) {
        companySearch({company: queryString}).then(response => {
          let list = [];
          response.data.forEach(element => {
            let object = {"value": element};
            list.push(object)
          });
          cb(list)
        })
      }


    }
  }
</script>

<style scoped rel="stylesheet/scss" lang="scss">
  .el-form-item {
    margin-bottom: 0 !important;
  }

  .item {
    margin-top: 10px;
    margin-right: 40px;
  }

  .yellow {
    fill: #ff9900 !important;
  }
</style>
